#include "IIC.h"

/**
  * @brief  I2C Initialization function
  * @param  void
  * @retval None
  */
void I2C_InitConfig(void)
{
    FL_GPIO_InitTypeDef GPIO_InitStruct;
    FL_I2C_MasterMode_InitTypeDef defaultInitStruct;

    GPIO_InitStruct.pin = FL_GPIO_PIN_12;
    GPIO_InitStruct.mode = FL_GPIO_MODE_DIGITAL;
    GPIO_InitStruct.outputType = FL_GPIO_OUTPUT_PUSHPULL;
    GPIO_InitStruct.pull = FL_DISABLE;
    GPIO_InitStruct.remapPin = FL_DISABLE;

    FL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.pin = FL_GPIO_PIN_11;
    GPIO_InitStruct.mode = FL_GPIO_MODE_DIGITAL;
    GPIO_InitStruct.outputType = FL_GPIO_OUTPUT_PUSHPULL;
    GPIO_InitStruct.pull = FL_DISABLE;
    GPIO_InitStruct.remapPin = FL_DISABLE;

    FL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    defaultInitStruct.clockSource = FL_RCC_I2C_CLK_SOURCE_RCHF;
    defaultInitStruct.baudRate = 40000;

    FL_I2C_MasterMode_Init(I2C, &defaultInitStruct); 
}

uint8_t I2C_Send_Bit(uint8_t BIT_def)
{
	uint32_t counter = 0;
	uint32_t stopstatus, startstatus;

    switch(BIT_def)
    {
        case STARTBIT:
            FL_I2C_Master_EnableI2CStart(I2C);
			do
			{
				startstatus = FL_I2C_Master_IsActiveFlag_Start(I2C);
				counter++;
			}while((startstatus != 0x01U) && (counter != I2C_TIMEOUT));
            break;
        case RESTARTBIT:
            FL_I2C_Master_EnableI2CRestart(I2C);
			do
			{
				startstatus = FL_I2C_Master_IsActiveFlag_Start(I2C);
				counter++;
			}while((startstatus != 0x01U) && (counter != I2C_TIMEOUT));
            break;
        case STOPBIT:
            FL_I2C_Master_EnableI2CStop(I2C);
			do
			{
				stopstatus = FL_I2C_Master_IsActiveFlag_Stop(I2C);
				counter++;
			}while((stopstatus != 0x01U) && (counter != I2C_TIMEOUT));
            break;
        default:
            break;
    }
    return 0; //ok
}
